package com.lanou3g.ptp.base.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanou3g.ptp.entity.Base;
import com.lanou3g.ptp.base.mapper.BaseMapper;
import com.lanou3g.ptp.base.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BaseServiceImpl implements BaseService {

    @Autowired
    private BaseMapper baseMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${REDIS_BASE_KEY_PREFIX}")
    private String REDIS_BASE_KEY_PREFIX;

    @Value("${REDIS_BASE_KEY_EXPIRE}")

    private Long REDIS_BASE_KEY_EXPIRE;

    //查询所有
    @Override
    public PageInfo<Base> findAll(Integer page,Integer size) {
        PageHelper.startPage(page,size);
        List<Base> all = baseMapper.findAll();
        return new PageInfo<>(all);
    }

    //根据名字模糊查询
    @Override
    public PageInfo<Base> findByKeyword(Integer page, Integer size,String keyword) {
        PageHelper.startPage(page,size);
        List<Base> byKeyword = baseMapper.findByKeyword("%" + keyword + "%");
        return new PageInfo<>(byKeyword);
    }

    @Override
    public void insert(Base base) {
        base.setCreateTime(new Date());
        base.setUpdateTime(new Date());
        baseMapper.insert(base);
    }

    @Override
    public void deleteById(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Long[] ids) {
        baseMapper.deleteByIds(ids);
    }

    @Override
    public void updateById(Long id,Base base) {
        base.setUpdateTime(new Date());
        baseMapper.updateById(id,base);
    }

    @Override
    public Base findById(Long id) {
        //设置key
        String s1 = REDIS_BASE_KEY_PREFIX + id;
        //通过key值 去redis 查有没有东西
        String s2 = redisTemplate.opsForValue().get(s1);
        if (s2==null){
            //redis没东西的情况
            //使用id去数据库查询
            Base byId = baseMapper.findById(id);
            //把查询的对象 序列化成 json 字符串
            String s = JSON.toJSONString(byId);
            //放进redis 设置时间
            redisTemplate.opsForValue().set(s1,s,REDIS_BASE_KEY_EXPIRE, TimeUnit.SECONDS);
            return byId;
        }else {
            //redis查询出结果  重新刷新 过期时间
            redisTemplate.expire(s1, REDIS_BASE_KEY_EXPIRE, TimeUnit.SECONDS);
            //把查询出的结果 反序列化成对象类型
            //返回对象
            return JSON.parseObject(s2, Base.class);
        }



    }

    @Override
    public List<Base> findByName(String keyword) {
        return baseMapper.findByKeyword(keyword);
    }
}
